package com.tuzhi.sys.web.controller;

import com.tuzhi.auth.vo.UserBaseInfo;
import com.tuzhi.common.constants.security.AuthConstant;
import com.tuzhi.sys.jpa.entity.SysRoleEntity;
import com.tuzhi.sys.jpa.entity.SysUserEntity;
import com.tuzhi.sys.service.SysRoleService;
import com.tuzhi.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 定义一些基础信息给其它APP应用调用 ，
 * 需要查询一些AUTH系统 相关的基础数据
 * 这些接口不对外开放，内部APP应用调用（不需要校验权限，原则上加入白名单 【后期加上】）
 */

@RestController
@RequestMapping("/4app/sys")
@Slf4j
public class SysUserOfAppController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService roleService;


    /**
     * 通过用户名，获取用户的基础信息
     *
     * @param userName
     * @return
     */
    @GetMapping("/getUserOfUserName/{userName}")
    public UserBaseInfo getUserOfUserName(@PathVariable("userName") String userName) {
        SysUserEntity sysUserEntity = sysUserService.getUserByUserName(userName);
        return entityTransUserBaseInfo(sysUserEntity);
    }

    /**
     * 通过用户Id，获取用户的基础信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserOfUserId/{userId}")
    UserBaseInfo getUserOfUserId(@PathVariable("userId") Long userId) {
        SysUserEntity sysUserEntity = sysUserService.get(userId);
        return entityTransUserBaseInfo(sysUserEntity);
    }

    private UserBaseInfo entityTransUserBaseInfo(SysUserEntity sysUserEntity) {
        if (sysUserEntity != null) {
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            userBaseInfo.setUserName(sysUserEntity.getUsername());
            userBaseInfo.setUserId(sysUserEntity.getId());
            userBaseInfo.setOrgId(sysUserEntity.getOrgId());
            userBaseInfo.setTel(sysUserEntity.getPhone());
            userBaseInfo.setNickName(sysUserEntity.getNickname());
            Set<String> roleNames = new HashSet<>();
            List<SysRoleEntity> roles = sysUserService.listRoles4UserName(sysUserEntity.getUsername());
            if (roles != null && !roles.isEmpty()) {
                roles.forEach(r -> {
                    roleNames.add(r.getName());
                });
                if (roleNames.contains(AuthConstant.ROLE_ADMIN)) {
                    userBaseInfo.setSupper(true);
                }
                if (roleNames.contains(AuthConstant.ROLE_MANAGER)) {
                    userBaseInfo.setDeptMgr(true);
                }
                userBaseInfo.setRoleSet(roleNames);
            }
            return userBaseInfo;
        }
        return null;
    }


}
